package cn.dlc.myapplication;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import android.widget.Button;
import butterknife.BindView;
import butterknife.OnClick;
import cn.dlc.commonlibrary.ui.base.BaseCommonActivity;
import cn.dlc.commonlibrary.utils.rv_tool.RecyclerViewUtil;
import cn.dlc.myapplication.adapter.BtAdapter;
import cn.dlc.myapplication.adapter.SimpleRecyclerAdapter;
import com.licheedev.myutils.LogPlus;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class MainActivity extends BaseCommonActivity {

    @BindView(R.id.btn_search)
    Button mBtnSearch;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    private EasyPermHelper mPermHelper;
    private static final int REQUEST_ENABLE_BT = 233;
    private BtAdapter mAdapter;
    private BluetoothAdapter mBluetoothAdapter;
    private BroadcastReceiver mReceiver;
    private AlertDialog mDialog;

    @Override
    protected int getLayoutID() {
        return R.layout.activity_main;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initRecyclerView();

        String[] permissions = { Manifest.permission.ACCESS_COARSE_LOCATION };
        mPermHelper = new EasyPermHelper(this, permissions, 10086);
        mPermHelper.rxResult().subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Boolean aBoolean) {
                checkAndOpenBluetooth();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

        mPermHelper.checkPermissions();

        initReceiver();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    private void initRecyclerView() {

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);
        RecyclerViewUtil.addDefaultDivider(mRecyclerView);
        mAdapter = new BtAdapter();
        mAdapter.setOnItemClickListener(
            new SimpleRecyclerAdapter.OnItemClickListener<BtAdapter.ViewHolder>() {
                @Override
                public void onItemClick(ViewGroup parent, BtAdapter.ViewHolder holder,
                    int position) {

                    BluetoothDevice item = mAdapter.getItem(position);

                    LogPlus.e("bond=" + item.getBondState());

                    if (item.getBondState() == BluetoothDevice.BOND_BONDING) {
                        showOneToast("设备正在绑定中，请勿多次绑定");
                    } else if (item.getBondState() == BluetoothDevice.BOND_NONE) {

                        BtPairUtil.createBond(item.getClass(), item);
                    } else {
                        showOneToast("设备已绑定");
                    }
                }
            });
        mRecyclerView.setAdapter(mAdapter);
    }

    /**
     * 检查并打开蓝牙
     */
    private void checkAndOpenBluetooth() {

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            // Device does not support Bluetooth
            showOneToast("不支持蓝牙");
            return;
        }

        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mPermHelper.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
            checkAndOpenBluetooth();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mPermHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @OnClick(R.id.btn_search)
    public void onViewClicked() {

        mAdapter.setNewData(null);

        mBluetoothAdapter.startDiscovery();
    }

    private void initReceiver() {
        mReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();

                final BluetoothDevice device =
                    intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                if (device == null) {
                    return;
                }

                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    // 找到设备
                    LogPlus.e(device.getName() + "\n" + device.getAddress());
                    mAdapter.addData(device);
                } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                    LogPlus.e("绑定状态变化，" + device.getName() + ",bond=" + device.getBondState());
                } else if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) {

                    abortBroadcast(); // 拦截配对广播，不让系统弹配对对话框

                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                    }

                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setTitle("绑定设备");

                    builder.setPositiveButton("绑定946666", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            BtPairUtil.setPin(device.getClass(), device, "946666");

                            dialog.dismiss();
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            BtPairUtil.cancelPairingUserInput(device.getClass(), device);
                        }
                    }).setCancelable(false);

                    mDialog = builder.show();
                }
            }
        };

        // Register the BroadcastReceiver
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        filter.setPriority(999); // 设置广播接收器优先级
        registerReceiver(mReceiver, filter);
    }
}
